from django import forms
from django.core.exceptions import ValidationError

from .models import Category, Article, Comment


# class CategoryForm(forms.Form):
#     name = forms.CharField(label='名称', max_length=32, validators=[validator_category_name])
#     comment = forms.CharField(label='描述', required=False)


class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        # fields = ['name', 'comment'] # 表单中列出哪些字段
        # fields = '__all__' # 表单中列出模型的所有字段
        exclude = []  # 表单中排除哪些字段


def validator_article_name_should_be_unique(value):
    if Article.objects.filter(title=value).exists():
        raise ValidationError('文章标题不能重复')


# def validator_category_name(value):
#     # 去查询是否已存在对应名称的类别
#     # 如果已存在，则要抛出ValidationError的异常
#     if Category.objects.filter(name=value).exists():
#         raise ValidationError('文章标题不能重复')

class ArticleForm(forms.ModelForm):
    # title = forms.CharField(label='标题', max_length=32, validators=[validator_category_name])

    class Meta:
        model = Article
        fields = '__all__'


class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ['content']
